// components/mPlayer/mPlayer.js
var songContent = {
  myAudio: {},
  playList: [],
  songResourceError: 0,
  requestTask: null
}
Component({

  /**
   * 组件的属性列表
   */
  properties: {

  },

  /**
   * 组件的初始数据
   */
  data: {
    showSongList: false,
    showPlayerPage: false,
    listHeight: 700, 
    isPlaying: false,
    playMode: 2, //1,单曲循环，2,列表循环，3,随机播放
    currentSongCover: 'http://dodododooo.com/wx/static/image/logo.jpg',
    currentSongTitle: 'dodododooo',
    currentSongArtist: 'dodododooo',
    songLrc: [{ time: 0, lrc: '' }],
    currentLrcIndex: 0,
    currentTime: 0,
    durationTime: 1,
    currentTimeToMinutes: '00:00',
    durationTimeToMinutes: '00:00',
    touchStartX: 0,
    touchStartY: 0,
    x: 0,
    y: 0,
    isSeek: false,
    seekValue: 0,
    showLrcPage: false,
    currentSongId: 0,
    songList: [{ "songId": 394796, "songTitle": "\u4f60\u7684\u67d4\u60c5\u6211\u6c38\u8fdc\u4e0d\u61c2", "artist": "\u6307\u5357\u9488", "artistId": 13587, "album": "\u6f14\u827a\u751f\u6daf", "albumId": 39101, "songImg": "http:\/\/p1.music.126.net\/olxkDKjxUt1deLr1OmcK5g==\/1799900534689324.jpg", "source": "netease" }, { "songId": 167874, "songTitle": "\u5f69\u8679", "artist": "\u8bb8\u5dcd", "artistId": 5770, "album": "\u5728\u8def\u4e0a\u2026\u2026", "albumId": 16954, "songImg": "http:\/\/p1.music.126.net\/c7QlVgWioB5SKJTh1gxquQ==\/69269232550737.jpg", "source": "netease" }, { "songId": 346139, "songTitle": "\u4e0d\u53ef\u4e00\u4e16", "artist": "Beyond", "artistId": 11127, "album": "Beyond XRCD Special", "albumId": 34113, "songImg": "http:\/\/p1.music.126.net\/Ajn-819hYNmrj1Atan0UIg==\/67070209295390.jpg", "source": "netease" }, { "songId": 155984, "songTitle": "\u5728\u96e8\u4e2d", "artist": "\u6c6a\u5cf0", "artistId": 5347, "album": "\u7231\u662f\u4e00\u9897\u5e78\u798f\u7684\u5b50\u5f39", "albumId": 15711, "songImg": "http:\/\/p1.music.126.net\/kPsFJNSYna6izLzHXziThw==\/599233837149718.jpg", "source": "netease" }, { "songId": 394756, "songTitle": "\u65e0\u6cd5\u9003\u8131", "artist": "\u6307\u5357\u9488", "artistId": 13587, "album": "\u65e0\u6cd5\u9003\u8131", "albumId": 39100, "songImg": "http:\/\/p1.music.126.net\/2zRXKjKtKHQmxM416uo6Mw==\/120946279070244.jpg", "source": "netease" }],  
  },

  attached: function () {
    var appInstance = getApp();
    this.setData({
      listHeight: appInstance.globalData.windowHeight - 500
    })
  },

  ready: function () {
    var me = this;
    songContent.playList = me.data.playMode < 3 ? me.data.songList : me.listShuffle(me.data.songList);
    const audioContext = wx.createInnerAudioContext();
    audioContext.autoplay = true;
    audioContext.onPlay(function () {
      me.setData({
        isPlaying: true,
      })
    })
    audioContext.onPause(function () {
      me.setData({
        isPlaying: false
      })
    })
    audioContext.onStop(function () {
      me.setData({
        isPlaying: false,
        currentTime: 0,
        durationTime: 1,
        currentLrcIndex: 0,
        currentTimeToMinutes: '00:00',
        durationTimeToMinutes: '00:00',
      })
    })
    audioContext.onEnded(function () {
      me.setData({
        isPlaying: false,
        currentTime: 0,
        durationTime: 1,
        currentLrcIndex: 0,
        currentTimeToMinutes: '00:00',
        durationTimeToMinutes: '00:00',
      })
      me.playNext()
    })
    audioContext.onTimeUpdate(function () {
      me.setData({
        isPlaying: true,
        currentLrcIndex: me.currentLrcIndex(audioContext.currentTime, me.data.songLrc),
        currentTime: audioContext.currentTime,
        durationTime: audioContext.duration,
        currentTimeToMinutes: me.secondsToMinutes(audioContext.currentTime),
        durationTimeToMinutes: me.secondsToMinutes(audioContext.duration),
      })
    })
    audioContext.onWaiting(function () {
      me.setData({
        isPlaying: false
      })
      return wx.showToast({ title: '歌曲资源加载中',icon: 'loading' });
    })
    
    songContent.myAudio = audioContext
  },
  /**
   * 组件的方法列表
   */
  methods: {
    secondsToMinutes: function (seconds) {
      var MM = Math.floor(seconds / 60),
        SS = Math.floor(seconds % 60);
      MM < 10 ? (MM = "0" + MM) : MM;
      SS < 10 ? (SS = "0" + SS) : SS;
      var time = MM + ":" + SS;
      return time;
    },
    currentLrcIndex: function (currentTime, songLrc) {
      var index = this.data.currentLrcIndex;
      for (var i = 0, len = songLrc.length; i < len; i++) {
        if (Math.abs(currentTime * 1000 - songLrc[i]['time']) < 300) {
          index = i;
          break;
        }
      }
      return index;
    },
    playerTouchStart: function (e) {
      this.setData({
        touchStartX: e.touches[0].clientX,
        touchStartY: e.touches[0].clientY,
      })
    },
    playerTouchMove: function (e) {
      var moveWidth = e.touches[0].clientX - this.data.touchStartX,
          moveHeight = e.touches[0].clientY - this.data.touchStartY;
      this.setData({
        x: moveWidth * 80,
        y: moveHeight * 80
      })
    },
    playerTouchEnd: function (e) {
      var target = e.currentTarget.id;
      var endDotX = e.changedTouches[0].clientX,
          endWidth = endDotX - this.data.touchStartX,
          endDotY = e.changedTouches[0].clientY,
          endHeight = endDotY - this.data.touchStartY;
      if (target === 'player-song-info' && Math.abs(endWidth) > 100) {
        endWidth < 0 ? this.playNext(true) : this.playPrev()
      } else if (target === 'player-list-bar' && endHeight > 100) {
        this.setData({
          showSongList: false
        })
      }
    },
    playerTouchCancel: (e) => {
      console.log(e)
    },


    playTab: function () {
      console.log(this.data, songContent)
      if (songContent.playList.length === 0) return wx.showToast({ title: '歌曲列表为空', icon: 'none' });
      if (!songContent.myAudio.src) {
        this.doPlay(songContent.playList[0])
      } else {
        songContent.myAudio.paused ? songContent.myAudio.play() : songContent.myAudio.pause();
      }
    },


    doPlay: function (song) {
      songContent.requestTask && songContent.requestTask.abort();
      this.setData({
        currentSongCover: song.songImg,
        currentSongTitle: song.songTitle,
        currentSongArtist: song.artist,
        currentSongId: song.songId
      })

      songContent.requestTask = wx.request({
        url: 'http://dodododooo.com/php/netease/musicPlay.php',
        data: {
          song: song.songId
        },
        success: (res) => {         
          songContent.myAudio.src = res.data.songUrl
          this.setData({
            songLrc: res.data.lrc.length === 0 ? [{ time: 0, lrc: 'No Lyric' }] : res.data.lrc,
          })
        },
        fail: (res) => {
          if (res.errMsg == "request:fail abort") return;
          wx.showToast({ title: '歌曲资源获取失败', icon: 'none' });
        },
        complete: (res) => {
          songContent.requestTask = null
        }
      })
      
    },


    playNext: function (isTab) {
      songContent.myAudio.stop();
      if (songContent.playList.length === 0) return wx.showToast({title: '歌曲列表为空', icon: 'none'});
      var currentSongIndex = this.findPlayingSongIndex(this.data.currentSongId);   
      var nextSongIndex = currentSongIndex === songContent.playList.length - 1 ? 0 : currentSongIndex + 1;
      if (isTab) {
        this.data.currentSongTitle == 'dodododooo' ? this.doPlay(songContent.playList[0]) : this.doPlay(songContent.playList[nextSongIndex]);
        return
      }
      this.data.playMode > 1 ? this.doPlay(songContent.playList[nextSongIndex]) : this.doPlay(songContent.playList[currentSongIndex]);
    },


    playPrev: function () {
      songContent.myAudio.stop();
      if (songContent.playList.length === 0) return;
      var currentSongIndex = this.findPlayingSongIndex(this.data.currentSongId);
      currentSongIndex === 0 ? this.doPlay(songContent.playList[songContent.playList.length - 1]) : this.doPlay(songContent.playList[currentSongIndex - 1]);
    },
    addSong: function (isPlay) {
      console.log(89898)
    },
    changePlayMode: function () {
      var mode = this.data.playMode === 3 ? 1 : ++this.data.playMode;
      this.setData({
        playMode: mode
      })
      songContent.playList = mode < 3 ? this.data.songList : this.listShuffle(this.data.songList);
    },
    findPlayingSongIndex: function (currentSongId) {
      if (currentSongId === 0) return 0;
      var currentIndex;
      songContent.playList.filter((item, index) => { 
        if (item.songId == currentSongId) 
          currentIndex = index;
      })
      return currentIndex ? currentIndex : 0;
    },
    listShuffle: function (array) {
      var arrayShuffle = array.concat();
      for (var i = arrayShuffle.length - 1; i >= 0; i--) {
        var randomIndex = Math.floor(Math.random() * (i + 1));
        var itemAtIndex = arrayShuffle[randomIndex];

        arrayShuffle[randomIndex] = arrayShuffle[i];
        arrayShuffle[i] = itemAtIndex;
      }
      return arrayShuffle;
    },

    showList: function () {
      this.setData({
        showSongList: true
      })
    },
    closeList: function (e) {
      this.setData({
        showSongList: false
      })
    },
    playThisSong: function(e) {
      if (e.currentTarget.dataset.song.songId == this.data.currentSongId) return
      this.doPlay(e.currentTarget.dataset.song)
    },
    removeSong: function (e) {
      songContent.myAudio.stop();
      songContent.myAudio.src = '';
      if (this.data.songList.length === 1) {
        this.emptySongList();
        return
      }
      this.playNext();
      var tempArray = this.data.songList.concat();
      tempArray.splice(e.currentTarget.dataset.songIndex, 1)
      this.data.playMode === 2 ? songContent.playList.splice(this.findPlayingSongIndex(e.currentTarget.dataset.songId), 1) : songContent.playList.splice(e.currentTarget.dataset.songIndex, 1)
      this.setData({
        songList: tempArray
      })
      return wx.showToast({ title: '歌曲已移除列表' });
    },
    emptySongList: function () {
      songContent.myAudio.stop();
      songContent.myAudio.src = '';
      songContent.playList = [];
      this.setData({
        songList: [],
        currentSongId: 0,
        currentTime: 0,
        currentTimeToMinutes: '00:00',
        durationTimeToMinutes: '00:00',
        currentSongCover: 'http://dodododooo.com/wx/static/image/logo.jpg',
        currentSongTitle: 'dodododooo',
        songLrc: [{ time: 0, lrc: '左右滑动切换歌曲' }]
      })
      return wx.showToast({ title: '歌曲列表已清空' });
    },
    catchtap: () => {
      return
    },

    closePlayerPage: function () {
      this.setData({
        showPlayerPage: false
      })
      wx.setNavigationBarColor({
        frontColor: '#ffffff',
        backgroundColor: '#ff0000',
        animation: {
          duration: 400,
          timingFunc: 'easeInOut'
        }
      })
    },
    openPlayerPage: function () {
      this.setData({
        showPlayerPage: true
      })
      wx.setNavigationBarColor({
        frontColor: '#ffffff',
        backgroundColor: '#791c1c',
        animation: {
          duration: 400,
          timingFunc: 'easeInOut'
        }
      })
    },
    doNothing: () => {
      return wx.showToast({ title: '样式图标。。。', icon: 'none' });
    },
    bindchange: function (e) {
      var value = e.detail.value / 100 * this.data.durationTime
      songContent.myAudio.seek(value)
      this.setData({
        isSeek: false,
      })
    },
    bindchanging: function (e) {
      this.setData({
        isSeek: true,
        seekValue: e.detail.value
      })
    },
    showLrcPage: function () {
      this.setData({
        showLrcPage: this.data.showLrcPage ? false : true
      })
    }
  }
})
